#!/bin/sh

STAGED_GO_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep ".go$")

if [[ "$STAGED_GO_FILES" = "" ]]; then
    exit 0
fi

PASS=true

for FILE in $STAGED_GO_FILES
do
    # 跳过vendor目录下的文件
    if [[ $FILE == *"vendor/"* ]];then
        continue
    fi

  # 如果当前文件没有被格式化，就格式化它
    UNFORMATTED=$(gofmt -l $FILE)
    if [[ "$UNFORMATTED" != "" ]];then
        gofmt -w $PWD/$UNFORMATTED
        if [[ $? != 0 ]]; then
            PASS=false
        fi
    fi

    # 上述 goimports, gofmt可能会对文件作出改动，
    # 所以此处将更改提交至暂存区
    git add $FILE

done

DIFF=$(git diff --cached --name-only --diff-filter=ACM | grep .)
if [[ "$DIFF" = "" ]]; then
    printf "\033[31m no changes added to commit \033[0m\n"
    exit 1
fi

if ! $PASS; then
    printf "\033[31m COMMIT FAILED \033[0m\n"
    exit 1
else
    printf "\033[32m COMMIT SUCCEEDED \033[0m\n"
fi

exit 0
